﻿#include "Package.hpp"
#include <iostream>
#include <string.h>

std::string Offset(std::string str, int offset);
bool CheckCipher(std::string str);

NetPackage::NetPackage()
{
    cmd = FOR = content_00 = ciphertext = plaintext = "";
}

NetPackage::~NetPackage()
{
}

//解密
void NetPackage::Decrypt()
{
    if (ciphertext.size() > 0)
    {
        char text[plaintext.size()];
        char tempStr[128];
        memset(text, 0, plaintext.size());
        strcpy(text, plaintext.c_str());
        //取偏移量
        int offset = atoi(&text[plaintext.size() - 1]);
        strcpy(text, Offset(plaintext, offset).c_str());
        strcpy(tempStr, strtok(text, ":"));
        account=tempStr;
        strtok(NULL, "{");
        strcpy(tempStr, strtok(NULL, "}"));
        strtok(tempStr, ":");
        cmd = strtok(NULL, ",");
        if (cmd == "HeartBeat")
        {
            FOR = content_00 = "";
            return;
        }
        else if (cmd == "GET")
        {
            strtok(NULL, ":");
            FOR = strtok(NULL, ",");
            content_00 = "";
            return;
        }

        strtok(NULL, ":");
        FOR = strtok(NULL, ",");
        strtok(NULL, ":");
        content_00 = strtok(NULL, ",");
        return;
    }
    std::cerr << "CipherText is Empty" << std::endl;
}

//加密
void NetPackage::Encrypt()
{
    if (ciphertext.size() > 0)
    {
        int offset = time(NULL) % 10;
        ciphertext = "COMMAND:" + cmd + ",FOR:" + FOR + ",CONTENT:" + content_00 + std::to_string(offset);
        ciphertext = Offset(ciphertext, -offset);
        return;
    }
    std::cerr << "CipherText is Empty" << std::endl;
}

//凯撒加密/解密
std::string Offset(std::string str, int offset)
{
    std::string ret;
    for (std::string::iterator item = str.begin(); item != str.end(); item++)
    {
        *item -= offset;
        ret += *item;
    }
    return ret;
}

//检查密文正确性
bool CheckCipher(std::string str)
{
    if (!isdigit(*str.end()))
    {
        return false;
    }
    if (str.size() < 31)
    {
        return false;
    }
    //查找冒号个数
    for (int i = 0, pos = 0; i < 2; i++)
    {
        pos = str.find(':', pos);
        if (pos == str.npos)
            return false;
    }
    //查找逗号
    if (str.find(':') == str.npos)
        return false;
    return true;
}

#pragma region 获取成员
std::string NetPackage::GetPlain()
{
    return plaintext;
}

std::string NetPackage::GetCipher()
{
    return ciphertext;
}

std::string NetPackage::Command()
{
    return cmd;
}
std::string NetPackage::Account()
{
    return account;
}

std::string NetPackage::ForText()
{
    return FOR;
}

std::string NetPackage::CONTENT()
{
    return content_00;
}
#pragma endregion

NetPackage::NetPackage(std::string plaintext)
{
    this->plaintext = plaintext;
}
void NetPackage::SetPlain(std::string str)
{
    plaintext = str;
}